package com.tanhua.service;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.Intercepter.UserHolder;
import com.tanhua.config.template.OssTemeplate;
import com.tanhua.dubbo.api.MovementApi;
import com.tanhua.dubbo.api.UserApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.exception.BusinessExecption;
import com.tanhua.model.domain.ErrorResult;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.mogo.Movement;
import com.tanhua.model.vo.MovementsVo;
import com.tanhua.model.vo.PageResult;
import com.tanhua.utils.Constants;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class MovementsService {
    @Autowired
    private OssTemeplate ossTemeplate;

    @DubboReference
    private MovementApi movementApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 发动态
     * @param movement
     * @param imageContent
     * @throws IOException
     */
    public void movements(Movement movement, MultipartFile[] imageContent) throws IOException {
     //1.判断文字内容是否为空
        if (StringUtils.isEmpty(movement.getTextContent())){
            throw new BusinessExecption(ErrorResult.contentError());
        }
        ArrayList<String> list = new ArrayList();
    //2.将照片上传至阿里云，并返回图片地址
        for (MultipartFile multipartFile : imageContent) {
            String upload = ossTemeplate.upload(multipartFile.getOriginalFilename(), multipartFile.getInputStream());
            list.add(upload);
        }
        //3.获取用户id
        Long id = UserHolder.getId();
        //4.将数据封装到movement对象
        movement.setUserId(id);
        movement.setMedias(list);
        //5.调用api
        movementApi.movements(movement);
    }

    /**
     * 查询个人动态
     * @param userId
     * @param page
     * @param pagesize
     * @return
     */
    public PageResult FindByUserId(Long userId, Integer page, Integer pagesize) {
        PageResult  pr =   movementApi.FindByUserId(userId,page,pagesize);
        List<Movement> items = (List<Movement>) pr.getItems();
        if (items==null){
            return pr;
        }
        UserInfo userInfo = userInfoApi.findById(userId);
        List<MovementsVo> list  =new ArrayList<>();
        for (Movement item : items) {
            MovementsVo vos =MovementsVo.init(userInfo,item);
            list.add(vos);
        }
        pr.setItems(list);
        return pr;
    }


    /**
     * 查询好友动态
     * @param page
     * @param pagesize
     * @return
     */
    public PageResult FindByFridends(Integer page, Integer pagesize) {
        //获取当前用户id
        Long id = UserHolder.getId();
        //调用api查询数据
        List<Movement> list = movementApi.FindByFridends(id, page, pagesize);
    return getPageResult(page,pagesize,list);
    }

    /**
     * 查询推荐动态
     * @param page
     * @param pagesize
     * @return
     */
    public PageResult RecommendMovements(Integer page, Integer pagesize) {
        //从redis中获取推荐数据
        String key = Constants.MOVEMENTS_RECOMMEND + UserHolder.getId();
        String redisValue = redisTemplate.opsForValue().get(key);
        List<Movement> movements = new ArrayList<>();
        //判断是否有数据
        if (StringUtils.isEmpty(redisValue)){
            //随机十条数据
           movements = movementApi.randomMovements(pagesize);
        }else {
            //将redis中的字符串切割成一个个pid
            String[] values = redisValue.split(",");
            //判断当前页的起始条数是否小于数组总数
            if ((page-1) * pagesize < values.length){
                List<Long> pids = Arrays.stream(values)
                        .skip((page - 1) * pagesize)
                        .limit(pagesize)
                        .map(e -> Long.valueOf(e))
                        .collect(Collectors.toList());
                movements = movementApi.findMovementByPids(pids);
            }
        }
        return getPageResult(page, pagesize, movements);
    }


    private PageResult getPageResult(Integer page, Integer pagesize, List<Movement> movements) {
        //非空判断
        if (CollUtil.isEmpty(movements)){
            return new PageResult();
        }
        List<Long> userId = CollUtil.getFieldValues(movements, "userId", Long.class);
        Map<Long, UserInfo> map = userInfoApi.MakeFriends(userId, null);
        List<MovementsVo> vos = new ArrayList<>();
        for (Movement movement : movements) {
            UserInfo userInfo = map.get(movement.getUserId());
            if (userInfo!=null){
                MovementsVo movementsVo = MovementsVo.init(userInfo, movement);
                vos.add(movementsVo);
            }
        }
        return new PageResult(page,pagesize,0,vos);
    }

    /**
     * 根据动态id查询动态
     * @param movementId
     * @return
     */
    public MovementsVo FindById(String movementId) {
      Movement movement= movementApi.FindById(movementId);
      if (movement!=null) {
          Long userId = movement.getUserId();
          UserInfo userInfo = userInfoApi.findById(userId);
         return MovementsVo.init(userInfo, movement);
      }
      return null;
    }

    /**
     * 动态点赞
     * @param id 动态id
     * @return
     */
    public Integer like(Integer id) {
        return null;
    }
}
